import { useState, useEffect, useCallback } from 'react';

export const useChromeHistory = (options = {}) => {
  const { maxResults = 10000, startTime = 0, endTime = null } = options;
  const [history, setHistory] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchHistory = useCallback(async () => {
    if (!chrome.history || !chrome.history.search) {
      setError('History API not available');
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const searchOptions = {
        text: '',
        maxResults,
        startTime
      };

      if (endTime) {
        searchOptions.endTime = endTime;
      }

      chrome.history.search(searchOptions, (results) => {
        if (chrome.runtime.lastError) {
          setError(chrome.runtime.lastError.message);
          setLoading(false);
        } else {
          setHistory(results || []);
          setLoading(false);
        }
      });
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  }, [maxResults, startTime, endTime]);

  useEffect(() => {
    fetchHistory();
  }, [fetchHistory]);

  return { history, loading, error, refetch: fetchHistory };
};

export const useHistoryStats = (history) => {
  const [stats, setStats] = useState({
    totalVisits: 0,
    uniqueDomains: 0,
    timeSpentByDomain: {},
    hourlyPattern: new Array(24).fill(0),
    dailyPattern: new Array(7).fill(0),
    categoryStats: {}
  });

  useEffect(() => {
    if (!history || history.length === 0) {
      setStats({
        totalVisits: 0,
        uniqueDomains: 0,
        timeSpentByDomain: {},
        hourlyPattern: new Array(24).fill(0),
        dailyPattern: new Array(7).fill(0),
        categoryStats: {}
      });
      return;
    }

    const domainHash = {};
    const hourlyVisits = new Array(24).fill(0);
    const dailyVisits = new Array(7).fill(0);
    let totalVisits = 0;

    history.forEach((item) => {
      const domain = extractDomain(item.url);
      const visitCount = item.visitCount || 1;
      const date = new Date(item.lastVisitTime);
      const hour = date.getHours();
      const day = date.getDay();

      totalVisits += visitCount;
      hourlyVisits[hour] += visitCount;
      dailyVisits[day] += visitCount;

      if (!domainHash[domain]) {
        domainHash[domain] = {
          visits: 0,
          category: categorizeDomain(domain)
        };
      }
      domainHash[domain].visits += visitCount;
    });

    const timeSpentByDomain = {};
    Object.keys(domainHash).forEach((domain) => {
      // Estimate time spent (assuming average visit duration)
      timeSpentByDomain[domain] = {
        visits: domainHash[domain].visits,
        estimatedMinutes: domainHash[domain].visits * 2, // Rough estimate
        category: domainHash[domain].category
      };
    });

    const categoryStats = {};
    Object.values(timeSpentByDomain).forEach(({ category, visits }) => {
      categoryStats[category] = (categoryStats[category] || 0) + visits;
    });

    setStats({
      totalVisits,
      uniqueDomains: Object.keys(domainHash).length,
      timeSpentByDomain,
      hourlyPattern: hourlyVisits,
      dailyPattern: dailyVisits,
      categoryStats
    });
  }, [history]);

  return stats;
};

function extractDomain(url) {
  try {
    const urlObj = new URL(url);
    return urlObj.hostname.replace('www.', '');
  } catch (e) {
    return url;
  }
}

function categorizeDomain(domain) {
  const lowerDomain = domain.toLowerCase();
  const categories = {
    productivity: ['google.com', 'docs.google.com', 'notion.so', 'trello.com'],
    entertainment: ['youtube.com', 'netflix.com', 'twitch.tv', 'spotify.com'],
    social: ['facebook.com', 'twitter.com', 'instagram.com', 'reddit.com'],
    education: ['wikipedia.org', 'stackoverflow.com', 'github.com', 'coursera.org'],
    news: ['news.google.com', 'cnn.com', 'bbc.com', 'nytimes.com']
  };

  for (const [category, sites] of Object.entries(categories)) {
    if (sites.some(site => lowerDomain.includes(site))) {
      return category;
    }
  }

  return 'other';
}

